package com.shenke.logging.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenke.logging.service.OperationLogService;
import com.shenke.logging.model.entity.OperationLog;
import com.shenke.logging.mapper.OperationLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
* @author 86180
* @description 针对表【operation_logs】的数据库操作Service实现
* @createDate 2025-06-19 21:12:36
*/
@Service
@Slf4j
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog>
    implements OperationLogService {

    /**
     * 保存操作日志，实现幂等性处理
     * @param operationLog 操作日志
     * @return 是否保存成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(OperationLog operationLog) {
        // 如果消息ID为空，直接保存
        if (!StringUtils.hasText(operationLog.getMessageId())) {
            log.warn("操作日志消息ID为空，无法保证幂等性：{}", operationLog);
            return super.save(operationLog);
        }
        // 检查是否已经处理过该消息
        LambdaQueryWrapper<OperationLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OperationLog::getMessageId, operationLog.getMessageId());
        long count = this.count(queryWrapper);
        if (count > 0) {
            log.info("操作日志消息已处理，跳过，消息ID：{}", operationLog.getMessageId());
            return true;
        }
        try {
            return super.save(operationLog);
        } catch (DuplicateKeyException e) {
            // 处理并发情况下可能出现的唯一索引冲突
            log.warn("操作日志保存时发生唯一索引冲突，消息ID：{}", operationLog.getMessageId(), e);
            return true;
        } catch (Exception e) {
            log.error("保存操作日志失败，消息ID：{}", operationLog.getMessageId(), e);
            // 其他异常继续抛出，触发消息重试机制
            throw e;
        }
    }
}




